import java.io.*;
import java.util.Arrays;

public class FileHandler {
    private File file;

    // 构造函数，接受文件路径作为参数
    public FileHandler(String filePath) {
        this.file = new File(filePath);
    }

    // 判断文件是否存在
    public boolean fileExists() {
        return file.exists();
    }

    // 创建新文件
    public void createFile() throws IOException {
        if (!fileExists()) {
            file.createNewFile();
            System.out.println("文件已创建：" + file.getName());
        } else {
            System.out.println("文件已存在：" + file.getName());
        }
    }

    // 删除文件
    public void deleteFile() {
        if (fileExists()) {
            file.delete();
            System.out.println("文件已删除：" + file.getName());
        } else {
            System.out.println("文件不存在：" + file.getName());
        }
    }

    // 读取文件内容
    public String readFile() throws IOException {
        StringBuilder content = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                content.append(line).append("\n");
            }
        }
        return content.toString();
    }

    // 写入文件内容
    public void writeFile(String data) throws IOException {
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(data);
            System.out.println("数据已写入文件：" + file.getName());
        }
    }

    // 异或加密写入文件内容
    public void writeXorEncryptedFile(String data, String key) throws IOException {
        byte[] bytes = data.getBytes();
        byte[] keyBytes = key.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) (bytes[i] ^ keyBytes[i % keyBytes.length]);
        }

        try (FileOutputStream fos = new FileOutputStream(this.file)) {
            fos.write(bytes);
            System.out.println("写入已经的加密数据的ASCII码：" + Arrays.toString(bytes));
            System.out.println("异或加密数据已写入文件：" + this.file.getName());
        }
    }

    // 异或解密读取文件内容
    public String readXorEncryptedFile(String key) throws IOException {
        byte[] bytes;
        try (FileInputStream fis = new FileInputStream(this.file)) {
            bytes = fis.readAllBytes();
        }

        System.out.println("获取未解密的数据ASCII码：" + Arrays.toString(bytes));
        byte[] keyBytes = key.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) (bytes[i] ^ keyBytes[i % keyBytes.length]);
        }

        return new String(bytes);
    }
}
